package com.polaris.live.ui.message.widget.single_message

import com.bumptech.glide.Glide
import com.polaris.live.adapter.MessageAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.databinding.MessageItemImageBinding
import com.polaris.live.im.db.entity.MessageEntity
import com.polaris.live.utils.image.BitmapUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.normal
import com.polaris.live.widget.ScaleImageView

/**
 * MessageImageItemHolder
 *
 * @author Created by lucas on 2023/10/22 18:32
 * @since 1.0.0
 */
class MessageImageItemHolder(
    adapter: MessageAdapter,
    binding: MessageItemImageBinding
) : AbstractMessageItemHolder<MessageItemImageBinding>(adapter, binding) {

    override fun bind(item: MessageEntity) {
        mBinding.apply {
            bindCommon(
                item,
                layoutTime.messageTextTime,
                layoutLeft,
                layoutRight,
                layoutLeftAvatar.avAvatar,
                layoutRightAvatar.avAvatar,
                layoutLeftAvatar.avFv,
                layoutRightAvatar.avFv,
                null,
                null,
                ivState,
                tvError
            )

            if (item.sender == UserManager.getUser().userId) {
                setRight(item)
            } else {
                setLeft(item)
            }
        }
    }

    private fun setLeft(item: MessageEntity) {
        mBinding.apply {
            handleSize(leftIvPic, item)

            Glide.with(root.context)
                .load(ImageUtils.imgPath(item.content))
                .run {
                    rightContent.getSize().let { (w, h) ->
                        override(w, h)
                    }
                }
                .normal()
                .into(leftIvPic)
        }
    }

    private fun setRight(item: MessageEntity) {
        mBinding.apply {
            handleSize(rightContent, item)

            Glide.with(root.context)
                .load(item.parameterBean?.localFilePath ?: ImageUtils.imgPath(item.content))
                .run {
                    rightContent.getSize().let { (w, h) ->
                        override(w, h)
                    }
                }
                .normal()
                .into(rightContent)
        }
    }

    private fun handleSize(imageView: ScaleImageView, item: MessageEntity) {
        val width = item.extBean?.imgWidth ?: BitmapUtils.MAX_WIDTH
        val height = item.extBean?.imgHeight ?: BitmapUtils.MAX_HEIGHT

        val (w, h) = ImageUtils.computeSize(width, height)

        imageView.setSize(w, h)
    }
}